package com.itita.ww2.game.user;

import java.util.HashMap;
import java.util.Map;

import com.itita.ww2.redis.RedisUtil;
import com.itita.ww2.redis.cache.Table;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.itita.ww2.data.PlayerConfig;
import com.itita.ww2.model.user.UserProfile;

/**
 * 科技管理器
 * @author NorthLan
 *
 */
public class UserScienceManager {
	private int uid;
	private UserProfile userProfile;
	private Map<String, UserScience> scienceMap; // 玩家所有已解锁的科技列表

	public UserScienceManager(UserProfile userProfile) {
		this.userProfile = userProfile;
		this.uid = userProfile.getUid();
		scienceMap = new HashMap<>();
	}

	//	/**
	//	 * 根据关卡ID决定解锁哪个科技
	//	 */
	//	public void unlockByMission(String missionId) {
	//		ISFSArray arr = MissionConfig.getUnlockData(missionId);
	//		for (int i = 0; i < arr.size(); ++i) {
	//			String k = arr.getUtfString(i);
	//			if (k.startsWith("S")) {
	//				scienceMap.put(k, new UserScience(k, 1));
	//			}
	//		}
	//		update();
	//	}

	public synchronized void load() {
		Table t = UserService.getInstance().getCacheUserDataTable();
		ISFSObject ret = SFSObject.newFromJsonData(t.getValue(RedisUtil.genericKey(this.uid), "science"));
		for (String key : ret.getKeys()) {
			this.scienceMap.put(key, UserScience.newFromJsonData(ret.getSFSObject(key)));
		}
	}

	public synchronized void update() {
		Table t = UserService.getInstance().getCacheUserDataTable();
		t.setValue(RedisUtil.genericKey(this.uid), "science", toSFSObject().toJson());
	}

	public ISFSObject toSFSObject() {
		ISFSObject ret = SFSObject.newInstance();
		for (UserScience us : scienceMap.values()) {
			ret.putSFSObject(us.getCode(), us.toSFSObject());
		}
		return ret;
	}

	public synchronized void initialize() {
		ISFSObject config = PlayerConfig.getGameInitScience();
		for (String key : config.getKeys()) {
			this.scienceMap.put(key, UserScience.newFromJsonData(config.getSFSObject(key)));
		}
		this.update();
	}

	public UserProfile getUserProfile() {
		return this.userProfile;
	}
}
